package com.xindacloud.sms.adapter.service.sms.impl;

import com.cmtelecom.text.sdk.MessageBuilder;
import com.cmtelecom.text.sdk.MessagingClient;
import com.cmtelecom.text.sdk.models.Channel;
import com.cmtelecom.text.sdk.models.Response;
import com.google.gson.Gson;
import com.xindacloud.sms.adapter.bo.SubmitMessageBO;
import com.xindacloud.sms.adapter.constant.CommonConstant;
import com.xindacloud.sms.adapter.entity.SmsSubmissionRecord;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.business.ISmsSubmissionRecordService;
import com.xindacloud.sms.adapter.service.sms.ISubmitMessageService;
import com.xindacloud.sms.adapter.utils.CommonUtils;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import com.xindacloud.sms.adapter.vo.SubmitMessageResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service("cmSubmitMessageService")
@Slf4j
public class CmSubmitMessageServiceImpl implements ISubmitMessageService<SubmitMessageBO, SubmitMessageResultVO> {

    @Autowired
    private ISmsSubmissionRecordService smsSubmissionRecordService;

    @Override
    public SubmitMessageResultVO submitMessage(SubmitMessageBO submitMessageBO) {

        final String messageId = CommonUtils.buildRandomUUID();

        final String recipient = submitMessageBO.getRecipient();
        final String[] split = recipient.split(CommonConstant.SEPARATOR_STR);
        final String apiSecret = submitMessageBO.getApiSecret();
        final String messageBody = submitMessageBO.getMessageBody();
        final String senderId = submitMessageBO.getSenderId();
        final Integer userId = submitMessageBO.getUserId();
        final String taskId = submitMessageBO.getTaskId();
        final String agentId = submitMessageBO.getAgentId();
        final BigDecimal costPrice = submitMessageBO.getCostPrice();
        final String countryCode = submitMessageBO.getCountryCode();
        final String countryPrefix = submitMessageBO.getCountryPrefix();

        try {
            final List<String> collect = Arrays.stream(split).map("00"::concat).collect(Collectors.toList());
            MessagingClient client = new MessagingClient(apiSecret);
            MessageBuilder messageBuilder = new MessageBuilder(messageBody, null, senderId,
                    String.join(CommonConstant.SEPARATOR_STR, collect).split(CommonConstant.SEPARATOR_STR));
            messageBuilder.WithAllowedChannels(new Channel[]{Channel.SMS});
            messageBuilder.WithReference(messageId);

            final Response.HttpResponseBody httpResponseBody = client.sendMessage(messageBuilder.Build());
            final Response.ResponseMessageDetail[] messages = httpResponseBody.messages;
            log.info("CM发送返回结果:{}",new Gson().toJson(httpResponseBody));
            AtomicReference<String> status = new AtomicReference<>("");
            SubmitMessageResultVO resultVO = new SubmitMessageResultVO();
            if (Objects.nonNull(messages) && messages.length > 0) {
                Arrays.asList(messages).forEach(detail -> {
                    resultVO.setErrorText(detail.messageDetails);
                    resultVO.setMessageId(messageId);
                    resultVO.setNetwork("");
                    resultVO.setSubmitStatus(Integer.parseInt(detail.messageErrorCode));
                    resultVO.setMessageCount(detail.parts);
                    status.set(StringUtils.isNotEmpty(detail.status) ? detail.status.toLowerCase() : "");

                });
            }
            final boolean messageIdNotEmpty = StringUtils.isNotEmpty(resultVO.getMessageId());
            final SmsSubmissionRecord submissionRecord = SmsSubmissionRecord.builder()
                    .messageId(resultVO.getMessageId())
                    .messageCount(resultVO.getMessageCount())
                    .errorText(resultVO.getErrorText())
                    .submitStatusCode(resultVO.getSubmitStatus())
                    .agentId(messageIdNotEmpty ? agentId : "")
                    .costPrice(messageIdNotEmpty ? costPrice : BigDecimal.ZERO)
                    .prefix(countryPrefix)
                    .countryCode(countryCode)
                    .finalStatus(status.get())
                    .sendTo(recipient)
                    .taskId(taskId)
                    .userId(userId)
                    .build();
            smsSubmissionRecordService.updateSmsSubmissionRecordFor(submissionRecord);
            //CM扣费在交货报告中清算
            return resultVO;
        } catch (Exception e) {
            log.error("CM发送短信异常:{}", e.getMessage(), e);
            throw new ServiceException("短信发送异常".concat(e.getMessage()), UnionResultHelp.StatusEnum.BadRequest.code());
        }

    }

}
